//
//  LoginPerformanceDiagnostic.swift
//  CMB250716
//
//  Created by Andy Lau on 16/7/25.
//

import SwiftUI
import Combine

/// 登录界面性能诊断工具
@MainActor
class LoginPerformanceDiagnostic: ObservableObject {
    
    // MARK: - 诊断结果
    @Published var diagnosticResults: [DiagnosticResult] = []
    @Published var isRunningDiagnostic: Bool = false
    @Published var currentTestName: String = ""
    
    // MARK: - 时间测量
    private var startTime: CFAbsoluteTime = 0
    private var measurements: [String: CFAbsoluteTime] = [:]
    
    // MARK: - 诊断项目
    enum DiagnosticTest: String, CaseIterable {
        case inputDebounceDelay = "输入防抖延迟测试"
        case onChangeProcessing = "onChange事件处理测试"
        case animationCalculation = "动画计算开销测试"
        case viewRedraw = "SwiftUI重绘测试"
        case timerScheduling = "Timer调度延迟测试"
        case hapticFeedback = "触觉反馈延迟测试"
        case viewHierarchy = "视图层级复杂度测试"
        case keyboardResponse = "键盘响应延迟测试"
    }
    
    struct DiagnosticResult {
        let testName: String
        let duration: Double // 毫秒
        let status: TestStatus
        let details: String
        let recommendation: String
        
        enum TestStatus {
            case excellent  // < 16ms (60fps)
            case good      // 16-33ms (30-60fps)
            case poor      // 33-100ms
            case critical  // > 100ms
            
            var color: Color {
                switch self {
                case .excellent: return .green
                case .good: return .blue
                case .poor: return .orange
                case .critical: return .red
                }
            }
            
            var description: String {
                switch self {
                case .excellent: return "优秀"
                case .good: return "良好"
                case .poor: return "较差"
                case .critical: return "严重"
                }
            }
        }
    }
    
    // MARK: - 开始诊断
    func startDiagnostic() {
        isRunningDiagnostic = true
        diagnosticResults.removeAll()
        
        // 按顺序执行所有测试
        Task {
            for test in DiagnosticTest.allCases {
                await runTest(test)
                try? await Task.sleep(nanoseconds: 500_000_000) // 0.5秒间隔
            }
            
            isRunningDiagnostic = false
        generateSummaryReport()
        }
    }
    
    // MARK: - 执行单个测试
    @MainActor
    private func runTest(_ test: DiagnosticTest) async {
        currentTestName = test.rawValue
        
        switch test {
        case .inputDebounceDelay:
            await testInputDebounceDelay()
        case .onChangeProcessing:
            await testOnChangeProcessing()
        case .animationCalculation:
            await testAnimationCalculation()
        case .viewRedraw:
            await testViewRedraw()
        case .timerScheduling:
            await testTimerScheduling()
        case .hapticFeedback:
            await testHapticFeedback()
        case .viewHierarchy:
            await testViewHierarchy()
        case .keyboardResponse:
            await testKeyboardResponse()
        }
    }
    
    // MARK: - 测试1: 输入防抖延迟
    private func testInputDebounceDelay() async {
        let startTime = CFAbsoluteTimeGetCurrent()
        
        // 模拟防抖处理
        await withCheckedContinuation { continuation in
            let _ = Timer.scheduledTimer(withTimeInterval: Double(LoginUIConfig.textFieldDebounceDelay) / 1000.0, repeats: false) { _ in
                continuation.resume()
            }
        }
        
        let duration = (CFAbsoluteTimeGetCurrent() - startTime) * 1000
        let status = getStatusForDuration(duration)
        
        let result = DiagnosticResult(
            testName: "输入防抖延迟",
            duration: duration,
            status: status,
            details: "当前防抖延迟: \(LoginUIConfig.textFieldDebounceDelay)ms",
            recommendation: duration > 50 ? "建议将防抖延迟减少到20-30ms" : "防抖延迟在合理范围内"
        )
        
        diagnosticResults.append(result)
    }
    
    // MARK: - 测试2: onChange事件处理
    private func testOnChangeProcessing() async {
        let startTime = CFAbsoluteTimeGetCurrent()
        
        // 模拟onChange处理逻辑
        let testInput = "12345678"
        let filtered = testInput.filter { $0.isNumber }
        let _ = String(filtered.prefix(8))
        
        // 模拟焦点状态处理
        let focusProcessing = true
        if focusProcessing {
            // 模拟触觉反馈
            if LoginUIConfig.enableHapticFeedback {
                let _ = UIImpactFeedbackGenerator(style: .light)
            }
        }
        
        let duration = (CFAbsoluteTimeGetCurrent() - startTime) * 1000
        let status = getStatusForDuration(duration)
        
        let diagnosticResult = DiagnosticResult(
            testName: "onChange事件处理",
            duration: duration,
            status: status,
            details: "处理输入过滤和焦点管理耗时: \(String(format: "%.2f", duration))ms",
            recommendation: duration > 10 ? "建议优化onChange处理逻辑" : "onChange处理性能良好"
        )
        
        DispatchQueue.main.async {
            self.diagnosticResults.append(diagnosticResult)
        }
    }
    
    // MARK: - 测试3: 动画计算开销
    private func testAnimationCalculation() async {
        let startTime = CFAbsoluteTimeGetCurrent()
        
        // 模拟边框动画计算
        for _ in 0..<100 {
            let opacity = LoginUIConfig.focusedBorderOpacity
            let unfocusedOpacity = LoginUIConfig.unfocusedBorderOpacity
            let _ = LoginUIConfig.borderHighlightDuration
            
            // 模拟动画插值计算
            let progress = Double.random(in: 0...1)
            let _ = unfocusedOpacity + (opacity - unfocusedOpacity) * progress
        }
        
        let duration = (CFAbsoluteTimeGetCurrent() - startTime) * 1000
        let status = getStatusForDuration(duration)
        
        let result = DiagnosticResult(
            testName: "动画计算开销",
            duration: duration,
            status: status,
            details: "边框动画计算耗时: \(String(format: "%.2f", duration))ms",
            recommendation: duration > 16 ? "建议简化动画效果或使用硬件加速" : "动画性能良好"
        )
        
        diagnosticResults.append(result)
    }
    
    // MARK: - 测试4: SwiftUI重绘测试
    private func testViewRedraw() async {
        let startTime = CFAbsoluteTimeGetCurrent()
        
        // 模拟多个@Published属性变化
        await withCheckedContinuation { continuation in
            DispatchQueue.main.async {
                // 模拟状态变化导致的重绘
                for _ in 0..<10 {
                    let _ = UUID() // 模拟状态变化
                }
                continuation.resume()
            }
        }
        
        let duration = (CFAbsoluteTimeGetCurrent() - startTime) * 1000
        let status = getStatusForDuration(duration)
        
        let result = DiagnosticResult(
            testName: "SwiftUI重绘",
            duration: duration,
            status: status,
            details: "视图重绘耗时: \(String(format: "%.2f", duration))ms",
            recommendation: duration > 16 ? "建议减少@Published属性或优化视图结构" : "视图重绘性能良好"
        )
        
        diagnosticResults.append(result)
    }
    
    // MARK: - 测试5: Timer调度延迟
    private func testTimerScheduling() async {
        let startTime = CFAbsoluteTimeGetCurrent()
        
        // 测试Timer创建和调度
        await withCheckedContinuation { continuation in
            let _ = Timer.scheduledTimer(withTimeInterval: 0.001, repeats: false) { _ in
                continuation.resume()
            }
        }
        
        let duration = (CFAbsoluteTimeGetCurrent() - startTime) * 1000
        let status = getStatusForDuration(duration)
        
        let result = DiagnosticResult(
            testName: "Timer调度延迟",
            duration: duration,
            status: status,
            details: "Timer调度耗时: \(String(format: "%.2f", duration))ms",
            recommendation: duration > 5 ? "建议使用DispatchQueue替代Timer" : "Timer调度性能良好"
        )
        
        diagnosticResults.append(result)
    }
    
    // MARK: - 测试6: 触觉反馈延迟
    private func testHapticFeedback() async {
        let startTime = CFAbsoluteTimeGetCurrent()
        
        // 测试触觉反馈
        if LoginUIConfig.enableHapticFeedback {
            let impactFeedback = UIImpactFeedbackGenerator(style: .light)
            impactFeedback.prepare()
            impactFeedback.impactOccurred()
        }
        
        let duration = (CFAbsoluteTimeGetCurrent() - startTime) * 1000
        let status = getStatusForDuration(duration)
        
        let result = DiagnosticResult(
            testName: "触觉反馈延迟",
            duration: duration,
            status: status,
            details: "触觉反馈处理耗时: \(String(format: "%.2f", duration))ms",
            recommendation: duration > 10 ? "建议预先准备触觉反馈生成器" : "触觉反馈性能良好"
        )
        
        diagnosticResults.append(result)
    }
    
    // MARK: - 测试7: 视图层级复杂度
    private func testViewHierarchy() async {
        let startTime = CFAbsoluteTimeGetCurrent()
        
        // 模拟复杂视图层级的布局计算
        let viewCount = 50 // 模拟视图数量
        for _ in 0..<viewCount {
            // 模拟布局计算
            let frame = CGRect(x: 0, y: 0, width: 100, height: 50)
            let _ = frame.insetBy(dx: 10, dy: 5)
        }
        
        let duration = (CFAbsoluteTimeGetCurrent() - startTime) * 1000
        let status = getStatusForDuration(duration)
        
        let result = DiagnosticResult(
            testName: "视图层级复杂度",
            duration: duration,
            status: status,
            details: "视图层级布局计算耗时: \(String(format: "%.2f", duration))ms",
            recommendation: duration > 16 ? "建议简化视图层级结构" : "视图层级性能良好"
        )
        
        diagnosticResults.append(result)
    }
    
    // MARK: - 测试8: 键盘响应延迟
    private func testKeyboardResponse() async {
        let startTime = CFAbsoluteTimeGetCurrent()
        
        // 模拟键盘响应处理
        await withCheckedContinuation { continuation in
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.05) {
                // 模拟键盘弹出的系统延迟
                continuation.resume()
            }
        }
        
        let duration = (CFAbsoluteTimeGetCurrent() - startTime) * 1000
        let status = getStatusForDuration(duration > 50 ? duration - 50 : duration) // 减去模拟的系统延迟
        
        let result = DiagnosticResult(
            testName: "键盘响应延迟",
            duration: duration,
            status: status,
            details: "键盘响应处理耗时: \(String(format: "%.2f", duration))ms",
            recommendation: "键盘响应主要受系统影响，建议优化其他环节"
        )
        
        diagnosticResults.append(result)
    }
    
    // MARK: - 辅助方法
    private func getStatusForDuration(_ duration: Double) -> DiagnosticResult.TestStatus {
        if duration < 16 {
            return .excellent
        } else if duration < 33 {
            return .good
        } else if duration < 100 {
            return .poor
        } else {
            return .critical
        }
    }
    
    // MARK: - 生成总结报告
    private func generateSummaryReport() {
        let criticalIssues = diagnosticResults.filter { $0.status == .critical }
        let poorIssues = diagnosticResults.filter { $0.status == .poor }
        
        print("\n=== 登录界面性能诊断报告 ===")
        print("严重问题 (>100ms): \(criticalIssues.count) 项")
        print("性能问题 (33-100ms): \(poorIssues.count) 项")
        
        if !criticalIssues.isEmpty {
            print("\n🚨 严重延迟问题:")
            for issue in criticalIssues {
                print("- \(issue.testName): \(String(format: "%.2f", issue.duration))ms")
                print("  建议: \(issue.recommendation)")
            }
        }
        
        if !poorIssues.isEmpty {
            print("\n⚠️ 性能优化建议:")
            for issue in poorIssues {
                print("- \(issue.testName): \(String(format: "%.2f", issue.duration))ms")
                print("  建议: \(issue.recommendation)")
            }
        }
        
        print("\n=== 诊断完成 ===")
    }
}

// MARK: - 诊断界面视图
struct LoginPerformanceDiagnosticView: View {
    @StateObject private var diagnostic = LoginPerformanceDiagnostic()
    
    var body: some View {
        NavigationView {
            VStack(spacing: 20) {
                if diagnostic.isRunningDiagnostic {
                    VStack(spacing: 15) {
                        ProgressView()
                            .scaleEffect(1.5)
                        
                        Text("正在执行: \(diagnostic.currentTestName)")
                            .font(.headline)
                            .foregroundColor(.blue)
                    }
                    .padding()
                } else {
                    Button("开始性能诊断") {
                        diagnostic.startDiagnostic()
                    }
                    .font(.headline)
                    .foregroundColor(.white)
                    .padding()
                    .background(Color.blue)
                    .cornerRadius(10)
                }
                
                if !diagnostic.diagnosticResults.isEmpty {
                    List(diagnostic.diagnosticResults, id: \.testName) { result in
                        VStack(alignment: .leading, spacing: 8) {
                            HStack {
                                Text(result.testName)
                                    .font(.headline)
                                
                                Spacer()
                                
                                Text(result.status.description)
                                    .font(.caption)
                                    .padding(.horizontal, 8)
                                    .padding(.vertical, 4)
                                    .background(result.status.color.opacity(0.2))
                                    .foregroundColor(result.status.color)
                                    .cornerRadius(8)
                            }
                            
                            Text("耗时: \(String(format: "%.2f", result.duration))ms")
                                .font(.subheadline)
                                .foregroundColor(.secondary)
                            
                            Text(result.details)
                                .font(.caption)
                                .foregroundColor(.secondary)
                            
                            Text(result.recommendation)
                                .font(.caption)
                                .foregroundColor(.blue)
                                .italic()
                        }
                        .padding(.vertical, 4)
                    }
                }
                
                Spacer()
            }
            .navigationTitle("登录性能诊断")
            .padding()
        }
    }
}

#Preview {
    LoginPerformanceDiagnosticView()
}